package com.desk.api.mqtt;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class MqttPublishServer {

  @Value("${smartDesk.broker}")
  private String broker;

  @Value("${smartDesk.username}")
  private String username;

  @Value("${smartDesk.password}")
  private String password;

  String clientid = "smartDesk_push_client";

  @Async
  public void publish(Object content, String topic) {
    int qos = 1;
    try (MqttClient client = new MqttClient(broker, clientid, new MemoryPersistence())) {
      // 连接参数
      MqttConnectOptions options = new MqttConnectOptions();
      // 设置用户名和密码
      options.setUserName(username);
      options.setPassword(password.toCharArray());
      options.setConnectionTimeout(60);
      options.setKeepAliveInterval(60);
      // 连接
      client.connect(options);
      // 创建消息并设置 QoS
      MqttMessage message = new MqttMessage(JSONUtil.toJsonStr(content).getBytes());
      message.setQos(qos);
      // 发布消息
      client.publish(topic, message);
      // 关闭连接
      client.disconnect();
    } catch (MqttException e) {
      log.error("mqtt publish error", e);
    }
  }
}
